package account

import (
    "github.com/gin-gonic/gin"
    "gorm.io/gorm"
    "iip/account/model"
    "iip/lib"
)


func (s *Account) SysAccountRoleSet(c *gin.Context) {

    req := &struct {
        ID int64 `uri:"id"`
    }{}
    if err := c.ShouldBindUri(req); err != nil {
        s.logger.Error(err.Error())
        lib.JsonError(c, err.Error())
        return
    }
    acc, err:= s.GetAccountByID(req.ID)


    req_ := &struct {
        RoleIDList   []int64  `form:"role_id_list" json:"role_id_list"   binding:""`
        RoleNameList []string `form:"role_name_list" json:"role_name_list" binding:""`
    }{}
    if err := c.ShouldBindJSON(req_); err != nil {
        lib.JsonError(c, err.Error())
        return
    }
    s.logger.Info("绑定角色资源", req_.RoleIDList)


    var role_list []*model.Role
    for _, role_id := range req_.RoleIDList {
        s.logger.Info("查找", role_id)
        res, err := s.GetRoleByID(role_id)
        if err != nil {
            s.logger.Error(err)
            lib.JsonError(c, err.Error())
            return
        }
        s.logger.Info("找到", res.Name)
        role_list = append(role_list, res)
    }
    for _, role_name := range req_.RoleNameList {
        s.logger.Info("查找", role_name)
        res, err := s.GetRoleByName(role_name)
        if err != nil {
            s.logger.Error(err)
            lib.JsonError(c, err.Error())
            return
        }
        s.logger.Info("找到", res.Name)
        role_list = append(role_list, res)
    }
    s.logger.Info("共查找到", len(role_list), "个角色")


    err = s.gorm().Transaction(func(tx *gorm.DB) error {

        if err := tx.Where(&model.AccountRole{AccountID: acc.ID}).Delete(&model.AccountRole{}).Error; err != nil {
            return err
        }

        for _, role := range role_list {
            ar := &model.AccountRole{}
            ar.ID = s.idgen.NextID()
            ar.AccountID = acc.ID
            ar.RoleID = role.ID
            if err := tx.Create(ar).Error; err != nil {
                return err
            }
        }
        return nil
    })
    if err != nil {
        s.logger.Error(err)
        lib.JsonError(c, err.Error())
        return
    }

    lib.JsonData(c, s.account_detail(acc))
}
